using Newtonsoft.Json;
using LiJ.Common.Core;
using LiJ.Http.Mos;
using LiJ.Framework.Official.Basic.Mos;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace LiJ.Framework.Official.Basic
{
	public class WxOffKfApi : WxOffBaseApi
	{
		/// <summary>
		///
		/// </summary>
		/// <param name="config">配置信息，如果这里不传，需要在程序入口静态 WxBaseApi.DefaultConfig 属性赋值</param>
		public WxOffKfApi(AppConfig config = null)
			: base(config)
		{
		}

		/// <summary>
		///   添加客服账号
		/// </summary>
		/// <param name="account">完整客服账号，格式为：账号前缀@公众号微信号</param>
		/// <param name="nickname">客服昵称，最长6个汉字或12个英文字符</param>
		/// <returns></returns>
		public async Task<WxBaseResp> AddKfAccountAsync(string account, string nickname)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfaccount/add";
			LHttpRequest.CustomBody = string.Format("{{\"kf_account\":\"{0}\",\"nickname\":\"{1}\"}}", account, nickname);
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		/// 邀请绑定客服帐号
		/// </summary>
		/// <param name="account">完整客服帐号，格式为：帐号前缀@公众号微信号</param>
		/// <param name="inviteWx">接收绑定邀请的客服微信号</param>
		/// <returns></returns>
		public async Task<WxBaseResp> InviteKfWorker(string account, string inviteWx)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfaccount/inviteworker";
			LHttpRequest.CustomBody = string.Format("{{\"kf_account\":\"{0}\",\"invite_wx\":\"{1}\"}}", account, inviteWx);
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///   修改客服账号
		/// </summary>
		/// <param name="account">完整客服账号，格式为：账号前缀@公众号微信号</param>
		/// <param name="nickname">客服昵称，最长6个汉字或12个英文字符</param>
		/// <returns></returns>
		public async Task<WxBaseResp> UpdateKFAccountAsync(string account, string nickname)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfaccount/update";
			LHttpRequest.CustomBody = string.Format("{{\"kf_account\":\"{0}\",\"nickname\":\"{1}\"}}", account, nickname);
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///   删除客服账号
		/// </summary>
		/// <param name="account">完整客服账号，格式为：账号前缀@公众号微信号</param>
		/// <returns></returns>
		public async Task<WxBaseResp> DeleteKFAccountAsync(string account)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfaccount/del?kf_account=" + account;
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///   设置客服账号头像
		/// </summary>
		/// <param name="account">完整客服账号，格式为：账号前缀@公众号微信号</param>
		/// <param name="fileReq">头像的文件信息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> UploadKFHeadImgAsync(string account, WxFileReq fileReq)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfaccount/uploadheadimg?kf_account=" + account;
			LHttpRequest.FileParameters.Add(new FileParameter("media", fileReq.file_stream, fileReq.file_name, fileReq.content_type));
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取客服基本信息列表
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetKFAccountListResp> GetKFAccountListAsync()
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/customservice/getkflist";
			return await base.RestCommonOffcialAsync<WxGetKFAccountListResp>(LHttpRequest, null);
		}

		/// <summary>
		///   获取在线客服列表
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetKfOnlineResp> GetKfOnlineList()
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/customservice/getonlinekflist";
			return await base.RestCommonOffcialAsync<WxGetKfOnlineResp>(LHttpRequest, null);
		}

		/// <summary>
		/// 创建会话
		/// </summary>
		/// <param name="account">完整客服帐号，格式为：帐号前缀@公众号微信号</param>
		/// <param name="openId">粉丝的openid</param>
		/// <returns></returns>
		public async Task<WxBaseResp> CreateKfSession(string account, string openId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfsession/create";
			LHttpRequest.CustomBody = string.Format("{{\"kf_account\":\"{0}\",\"openid\":\"{1}\"}}", account, openId);
			return await base.RestCommonOffcialAsync<WxGetKfOnlineResp>(LHttpRequest, null);
		}

		/// <summary>
		/// 关闭会话
		/// </summary>
		/// <param name="account">完整客服帐号，格式为：帐号前缀@公众号微信号</param>
		/// <param name="openId">粉丝的openid</param>
		/// <returns></returns>
		public async Task<WxBaseResp> CloseKfSession(string account, string openId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfsession/close";
			LHttpRequest.CustomBody = string.Format("{{\"kf_account\":\"{0}\",\"openid\":\"{1}\"}}", account, openId);
			return await base.RestCommonOffcialAsync<WxGetKfOnlineResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取用户客服会话信息
		/// </summary>
		/// <param name="openId"></param>
		/// <returns></returns>
		public async Task<WxGetUserKfSessionResp> GetUserKfSession(string openId)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfsession/getsession?openid=" + openId;
			return await base.RestCommonOffcialAsync<WxGetUserKfSessionResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取客服的用户会话列表
		/// </summary>
		/// <param name="account">客服账号</param>
		/// <returns></returns>
		public async Task<WxGetKfSessionsByAccountResp> GetKfSessionsByAccount(string account)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfsession/getsessionlist?kf_account=" + account;
			return await base.RestCommonOffcialAsync<WxGetKfSessionsByAccountResp>(LHttpRequest, null);
		}

		/// <summary>
		///  获取未接入会话列表
		/// </summary>
		/// <returns></returns>
		public async Task<WxGetKfWaitUserListResp> GetKfWaitUserList()
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Get;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/kfsession/getwaitcase?";
			return await base.RestCommonOffcialAsync<WxGetKfWaitUserListResp>(LHttpRequest, null);
		}

		/// <summary>
		///  发送一般的客服消息
		///   包含：image-图片,voice-语音，mpnews-图文消息，wxcard-卡券
		/// </summary>
		/// <param name="openId"></param>
		/// <param name="msgType">消息类型</param>
		/// <param name="mediaId">素材id，当是wxcard类型时，传入cardId，其他正常传入medaid</param>
		/// <param name="kfAccount">如果不为空，则以当前客服身份发送消息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SenKfMediaMsgAsync(string openId, string msgType, string mediaId = null, string kfAccount = null)
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"touser\":\"").Append(openId).Append("\",");
			stringBuilder.Append("\"msgtype\":\"").Append(msgType).Append("\",");
			stringBuilder.Append("\"").Append(msgType).Append("\":");
			stringBuilder.Append("{\"media_id\":\"").Append(mediaId).Append("\"}");
			if (!string.IsNullOrEmpty(kfAccount))
			{
				stringBuilder.Append(",\"customservice\":{\"kf_account\":\"").Append(kfAccount).Append("\"}");
			}
			stringBuilder.Append("}");
			return await this.SendKfMsgAsync(stringBuilder.ToString());
		}

		/// <summary>
		///  发送一般的客服消息
		///   包含：text-文本，image-图片,voice-语音，mpnews-图文消息，wxcard-卡券
		/// </summary>
		/// <param name="openId"></param>
		/// <param name="content">素材id，如果是text填空，当是wxcard类型时，传入cardId，其他正常传入meidaid</param>
		/// <param name="kfAccount">如果不为空，则以当前客服身份发送消息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SenKfTextMsgAsync(string openId, string content, string kfAccount = null)
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"touser\":\"").Append(openId).Append("\",");
			stringBuilder.Append("\"msgtype\":\"text\",");
			stringBuilder.Append("\"text\":");
			stringBuilder.Append("{\"content\":\"").Append(content).Append("\"}");
			if (!string.IsNullOrEmpty(kfAccount))
			{
				stringBuilder.Append(",\"customservice\":{\"kf_account\":\"").Append(kfAccount).Append("\"}");
			}
			stringBuilder.Append("}");
			return await this.SendKfMsgAsync(stringBuilder.ToString());
		}

		/// <summary>
		///  发送视频消息
		/// </summary>
		/// <param name="openId"></param>
		/// <param name="mediaId">必填，素材id</param>
		/// <param name="thumbMediaId">必填， 缩略图id</param>
		/// <param name="title"></param>
		/// <param name="description"></param>
		/// <param name="kfAccount">如果不为空，则以当前客服身份发送消息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SenKfVideoMsgSync(string openId, string mediaId, string thumbMediaId, string title = "", string description = "", string kfAccount = "")
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"touser\":\"").Append(openId).Append("\",");
			stringBuilder.Append("\"msgtype\":\"video\",");
			stringBuilder.Append("\"video\":{");
			stringBuilder.Append("\"media_id\":\"").Append(mediaId).Append("\",");
			stringBuilder.Append("\"thumb_media_id\":\"").Append(thumbMediaId).Append("\",");
			stringBuilder.Append("\"title\":\"").Append(title).Append("\",");
			stringBuilder.Append("\"description\":\"").Append(description).Append("\"");
			stringBuilder.Append("}");
			if (!string.IsNullOrEmpty(kfAccount))
			{
				stringBuilder.Append(",\"customservice\":{\"kf_account\":\"").Append(kfAccount).Append("\"}");
			}
			stringBuilder.Append("}");
			return await this.SendKfMsgAsync(stringBuilder.ToString());
		}

		/// <summary>
		///  发送音乐消息
		/// </summary>
		/// <param name="openId"></param>
		/// <param name="thumbMediaId"></param>
		/// <param name="musicurl">音乐链接</param>
		/// <param name="hqmusicurl">高品质音乐链接，wifi环境优先使用该链接播放音乐</param>
		/// <param name="title"></param>
		/// <param name="description"></param>
		/// <param name="kfAccount">如果不为空，则以当前客服身份发送消息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SenKfMusicMsgAsync(string openId, string musicurl, string hqmusicurl, string thumbMediaId, string title = "", string description = "", string kfAccount = "")
		{
			StringBuilder stringBuilder = new StringBuilder("{");
			stringBuilder.Append("\"touser\":\"").Append(openId).Append("\",");
			stringBuilder.Append("\"msgtype\":\"music\",");
			stringBuilder.Append("\"music\":{");
			stringBuilder.Append("\"title\":\"").Append(title).Append("\",");
			stringBuilder.Append("\"description\":\"").Append(description).Append("\",");
			stringBuilder.Append("\"thumb_media_id\":\"").Append(thumbMediaId).Append("\",");
			stringBuilder.Append("\"musicurl\":\"").Append(musicurl).Append("\",");
			stringBuilder.Append("\"hqmusicurl\":\"").Append(hqmusicurl).Append("\"");
			stringBuilder.Append("}");
			if (!string.IsNullOrEmpty(kfAccount))
			{
				stringBuilder.Append(",\"customservice\":{\"kf_account\":\"").Append(kfAccount).Append("\"}");
			}
			stringBuilder.Append("}");
			return await this.SendKfMsgAsync(stringBuilder.ToString());
		}

		/// <summary>
		///  发送非素材多图文消息（不能超过8条）
		/// </summary>
		/// <param name="openId"></param>
		/// <param name="articles">图文信息，不能超过8条</param>
		/// <param name="kfAccount">如果不为空，则以当前客服身份发送消息</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SenKfArticlesMsgAsync(string openId, List<WxArticleInfo> articles, string kfAccount = "")
		{
			string msgContent = JsonConvert.SerializeObject(new
			{
				touser = openId,
				msgtype = "news",
				news = new
				{
					articles
				},
				customservice = (string.IsNullOrEmpty(kfAccount) ? new
				{
					kf_account = kfAccount
				} : null)
			}, Formatting.Indented, new JsonSerializerSettings
			{
				NullValueHandling = NullValueHandling.Ignore
			});
			return await this.SendKfMsgAsync(msgContent);
		}

		/// <summary>
		///  发送客服最终走的方法
		/// </summary>
		/// <param name="msgContent"></param>
		/// <returns></returns>
		private async Task<WxBaseResp> SendKfMsgAsync(string msgContent)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/cgi-bin/message/custom/send";
			LHttpRequest.CustomBody = msgContent;
			return await base.RestCommonOffcialAsync<WxBaseResp>(LHttpRequest, null);
		}

		/// <summary>
		///   获取客服的聊天记录列表
		/// </summary>
		/// <param name="msgReq"></param>
		/// <returns></returns>
		public async Task<WxGetKfMsgListResp> GetKfMsgList(WxGetKfMsgListReq msgReq)
		{
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = "https://api.weixin.qq.com" + "/customservice/msgrecord/getmsglist";
			LHttpRequest.CustomBody = JsonConvert.SerializeObject(msgReq);
			return await base.RestCommonOffcialAsync<WxGetKfMsgListResp>(LHttpRequest, null);
		}
	}
}
